package pattern.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import pattern.WorkServiceTool;
import pattern.annontations.CacheDel;
import pattern.annontations.Menu;
import pattern.annontations.Secure;
import pattern.cache.InitCache;
import pattern.constant.CacheKeyConstant;
import pattern.dto.SysParam;
import pattern.dto.model.system.ParamAddOrUpdateModel;
import pattern.dto.model.system.ParamPageModel;
import pattern.dto.response.system.ParamPageResponse;
import pattern.enums.dict.common.YesOrNotEnum;
import pattern.model.BaseIdModel;
import pattern.result.ResponseData;
import pattern.result.ResponsePage;
import pattern.result.ResponseResultStatus;
import pattern.routing.WorkMainApiRouting;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.Date;
import java.util.Objects;

/**
 * @author Simon
 * @date 2021-05-10
 */
@Api(tags = "系统参数")
@RestController
@RequestMapping(value = WorkMainApiRouting.SysParam.BASE)
@Menu(menuName = "param", menuUri = "param", foundational = false)
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Secure
@Slf4j
public class SysParamController {

    private final InitCache initCache;

    @ApiOperation(value = "获取缓存参数值")
    @GetMapping(WorkMainApiRouting.SysParam.GET_CACHE)
    @Menu(verify = false)
    public ResponseData<SysParam> getCache(@PathVariable String key) {
        var get = initCache.params.GET(key);
        if (get.isSuccess()) {
            return new ResponseData<>(get.getValue());
        } else {
            var sysParam = WorkServiceTool.getSysParamService().getBaseMapper().selectOne(new QueryWrapper<SysParam>().lambda().eq(SysParam::getKey, key));
            if (Objects.nonNull(sysParam)) {
                initCache.params.put(key, sysParam);
                return new ResponseData<>(sysParam);
            }
        }
        return new ResponseData<>(ResponseResultStatus.NON_EXISTENT);
    }

    @ApiOperation(value = "查询")
    @GetMapping(WorkMainApiRouting.SysParam.LIST)
    @Secure(actionUri = "param:search", actionName = "search", actionNote = "param")
    public ResponsePage<ParamPageResponse> search(ParamPageModel model) {
        return WorkServiceTool.getSysParamService().pageResponse(model, ParamPageResponse.class);
    }

    @ApiOperation(value = "详情")
    @GetMapping(WorkMainApiRouting.SysParam.DETAIL)
    @Secure(actionUri = "param:search")
    public ResponseData<SysParam> detail(@PathVariable Integer id) {
        return new ResponseData<>(WorkServiceTool.getSysParamService().getById(new BaseIdModel<>(id)));
    }

    @ApiOperation(value = "修改")
    @PutMapping
    @Secure(actionUri = "param:edit", actionName = "edit", actionNote = "param")
    @CacheDel(CacheKeyConstant.SysParam.PARAM_KEY)
    public ResponseData<Boolean> edit(@Valid @RequestBody ParamAddOrUpdateModel model) {
        if (Objects.isNull(model.getId())) {
            return new ResponseData<>(ResponseResultStatus.ILLEGAL_PARAMETER);
        }
        if (WorkServiceTool.getSysParamService().getById(model.getId()).getBuiltIn().equals(YesOrNotEnum.YES.getCode())) {
            return new ResponseData<>(ResponseResultStatus.BUILT);
        }
        if (StringUtils.isBlank(model.getDefVal())) {
            model.setDefVal(model.getVal());
        }
        //修改子项
        var flag = Objects.nonNull(WorkServiceTool.getSysParamService().saveOrUpdate(model));
        return new ResponseData<>(flag);
    }

    @ApiOperation(value = "新增")
    @PostMapping
    @Secure(actionUri = "param:add", actionName = "add", actionNote = "param")
    @CacheDel(CacheKeyConstant.SysParam.PARAM_KEY)
    public ResponseData<Boolean> add(@Valid @RequestBody ParamAddOrUpdateModel model) {
        if (StringUtils.isBlank(model.getDefVal())) {
            model.setDefVal(model.getVal());
        }
        model.setCreateTime(new Date());
        return new ResponseData<>(Objects.nonNull(WorkServiceTool.getSysParamService().saveOrUpdate(model)));
    }

    @ApiOperation(value = "删除")
    @DeleteMapping(WorkMainApiRouting.SysParam.DELETE)
    @Secure(actionUri = "param:remove", actionName = "delete", actionNote = "param")
    @CacheDel(CacheKeyConstant.SysParam.PARAM_KEY)
    public ResponseData<Boolean> delete(@PathVariable Integer[] id) {
        if (WorkServiceTool.getSysParamService().listByIds(Arrays.asList(id.clone())).stream().anyMatch(e -> e.getBuiltIn().equals(YesOrNotEnum.YES.getCode()))) {
            return new ResponseData<>(ResponseResultStatus.BUILT);
        }
        return new ResponseData<>(WorkServiceTool.getSysParamService().removeByIds(new BaseIdModel<>(Arrays.asList(id.clone()))));
    }

}
